var station 	= "";
var pollInterval = 10; // in minutes

getprefs();

var url		= baseUrl(); 
var currentXML	= "http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml";

function goToWeather(){
	chrome.tabs.create({url: url});
}

function init(){
	window.setTimeout(startUpdate,0);
}

function scheduleRequest(){
	window.setTimeout(startUpdate,pollInterval * 60000);
}

function startUpdate(){
	getWeather();
	scheduleRequest();
}

function getWeather(){
	$.ajax({
		url: 	currentXML,
		type:	"GET",
		data: 	({query : station}),
		cache:	false,
		timeout: 5000,
		dataType: 'xml',
		error: function(){
			updateText("Error");
			url = baseUrl();
		},
		success: function(xml){
			// Update the text of the element
			updateText(
				jQuery.sprintf(
					"%s%s (%s)",
					getText(xml,"temp_f"),
					String.fromCharCode(176),
					getText(xml,"weather")
				)
			);

			// Update the icon
			$("#condition_icon").attr("src",
					jQuery.sprintf("%s/%s%s",
						"images",
						getText(xml,"icon"),
						getText(xml,"icon_url_name")
					)
				);

			url = getText(xml,"forecast_url");
		}
	});
}

function getText(xml,str){
	return $(xml).find(str).text();
}

function baseUrl(){
	return "http://www.wunderground.com/"; 
}

function updateText(text){
	$("#current_weather").text(text);
}
